import WebHeader from '@/www/components/WebHeader'
import WebFooter from '@/www/components/WebFooter'
import { getQuote, uploadFile, postQuoteOrder } from '@/apiv2/quote'

const CODE = 'SpecialtyCard'
const COUNT_PER_UNIT = 100

export default {
  components: { WebHeader, WebFooter },
  data() {
    return {
      dto: undefined,
      positionCount: undefined,
      quoteData: undefined,
      checkValue: {
        flagPerforating: false,
        flagRoundCorners: false,
        flagFrontStamping: false,
        flagReverseStamping: false,
        flagStampingNumber: false,
        flagColorlessBump: false,
        flagPressLine: false,
        flagBeerPinholeLine: false,
        flagHairLineShipping: false,
        flagCutFinished: false,
        flagCut: false,
      },
      quoteValue: {
        category: undefined,
        lamination: undefined,
        style: 1,
        side: '单面',
        quantity: undefined,
        size: undefined,
        customLength: undefined,
        customWidth: undefined,
        brightFilm: 'single',
        mattFilm: 'single',
        perforating: '4mm',
        frontStamping: undefined,
        frontStampingColor: undefined,
        reverseStamping: undefined,
        reverseStampingColor: undefined,
        colorlessBumpLength: undefined,
        colorlessBumpWidth: undefined,
        cutFinishedLength: undefined,
        cutFinishedWidth: undefined,
        pressLineCount: 1,
        flagBeerPinholeLineCount: 1,
        cut: 1,
      },
      processSelectOptions: {
        brightFilm: [
          {value: 'single', label: '单面'},
          {value: 'double', label: '双面'}
        ],
        perforating: [
          {value: '3mm', label: '3mm'},
          {value: '4mm', label: '4mm'},
          {value: '5mm', label: '5mm'}
        ],
        side: [
          {value: 'single', label: '单面'},
          {value: 'double', label: '双面'},
        ]
      },
      user: undefined,
      customSize: false,
      customLength: undefined,
      customWidth: undefined,
      quote: undefined,
      quoteList: undefined,
      detail: undefined,
      category: undefined,
      lamination: undefined,
      size: undefined,
      quantity: undefined,
      fileList: [],
      maxWidth: 200,
      logic: undefined,
      postData: {
        quantity: undefined,
        detail: undefined,
        amount: undefined,
        fileIds: undefined
      }
    }
  },

  created(){
    const user = JSON.parse(localStorage.getItem('user'))
    this.user = user

    getQuote(CODE).then(res => {
      let quoteData = res.config
      this.quoteValue.category = quoteData.cateData.list[0]
      this.quoteValue.size = quoteData.sizeData.list[0]
      this.quoteValue.quantity = quoteData.stepData.list[0]
      this.quoteData = quoteData
      this.dto = res
    })
  },

  methods: {

    getPricePerPosition(){
      let {quoteData,quoteValue} = this
      let price = undefined
      quoteData.cateData.list.forEach(item => {
        if(item.name == quoteValue.category){
          price = item.price
        }
      })
      return price
    },

    getPriceFromStampingSize(size){
      let quoteData = this.quoteData
      let price = 0.0;
      quoteData.process.stamping.forEach(item => {
        if(size == item.name){
          price = parseFloat(item.price)
        }
      })
      return price
    },

    getQuote(){
      let detail = ''
      let {quoteData,quoteValue,checkValue,customSize,postData} = this
      const {cardPosition} = quoteData.param
      let length = undefined
      let width = undefined
      if(quoteValue.customLength && quoteValue.customWidth && customSize){
        length = parseInt(quoteValue.customLength)
        width = parseInt(quoteValue.customWidth)
      }else if(quoteValue.size){
        length = parseInt(quoteValue.size.split('*')[0])
        width = parseInt(quoteValue.size.split('*')[1])
      }

      detail += '尺寸' + length + '*' + width +'，'
        + quoteValue.category +'，'
        + quoteValue.style + '款，'
        + quoteValue.side + '，'
        + (parseInt(quoteValue.quantity) * parseInt(quoteValue.style)) + '盒，'
      console.log(detail)

      const POSITION_LENGTH = parseInt(cardPosition.split('*')[0])
      const POSITION_WIDTH = parseInt(cardPosition.split('*')[1])
      const POSITION_COUNT = parseInt(this.caculatePositionCount(length,width,POSITION_LENGTH,POSITION_WIDTH))
      console.log('尺寸占用卡片位： ' + POSITION_COUNT)
      //this.positionCount = positionCount

      if(quoteValue.quantity > 5 && quoteValue < 10){
        quoteValue.quantity = 10
        this.quoteValue = quoteValue
      }

      let quoteList = []

      if(true){
        if(checkValue.flagPerforating){
          detail += '打孔' + quoteValue.perforating + '，'
        }

        if(checkValue.flagRoundCorners){
          detail += '切圆角，'
        }

        if(checkValue.flagFrontStamping){
          detail += '正面烫金(' + quoteValue.frontStamping.name + '，' + quoteValue.frontStampingColor + ')，'
        }

        if(checkValue.flagReverseStamping){
          detail += '反面烫金(' + quoteValue.reverseStamping.name + '，' + quoteValue.reverseStampingColor + ')，'
        }

        if(checkValue.flagStampingNumber){
          detail += '烫金号码，'
        }

        if(checkValue.flagColorlessBump){
          detail += '无色凹凸(' + quoteValue.colorlessBumpLength + '*' + quoteValue.colorlessBumpWidth + ')，'
        }

        if(checkValue.flagPressLine){
          detail += '压线(' + quoteValue.pressLineCount + '条)，'
        }

        if(checkValue.flagBeerPinholeLine){
          detail += '啤针孔线(' + quoteValue.flagBeerPinholeLineCount + '条)，'
        }

        if(checkValue.flagHairLineShipping){
          detail += '毛边出货，'
        }

        if(checkValue.flagCutFinished){
          detail += '切成品(' + quoteValue.cutFinishedLength + '*' + quoteValue.cutFinishedWidth + ')，'
        }

        if(checkValue.flagCut){
          detail += '模切(' + quoteValue.cut + '模)，'
        }
      }

      quoteData.stepData.list.forEach(i => {
        const QTY = parseInt(i) * parseInt(quoteValue.style)//阶梯盒数
        const QUANTITY = QTY * COUNT_PER_UNIT//阶梯张数
        let PROCESS_QUANTITY = parseFloat(QUANTITY / 500)
        PROCESS_QUANTITY = PROCESS_QUANTITY < 1.0 ? 1.0 : PROCESS_QUANTITY

        let sku = undefined
        quoteData.skuList.forEach(item => {
          if(item.name == quoteValue.category && parseInt(item.quantity) == parseInt(i)){
            sku = item
          }
        })

        const MATERIAL_AMOUNT = parseFloat(sku.price) * parseFloat(quoteValue.style) * parseFloat(POSITION_COUNT)

        let processAmount = 0

        if(checkValue.flagPerforating){
          console.log('flagPerforating')
          processAmount += parseFloat(quoteData.process.perforating) * PROCESS_QUANTITY
          console.log(processAmount)
        }

        if(checkValue.flagRoundCorners){
          console.log('flagRoundCorners')
          processAmount += parseFloat(quoteData.process.roundCorners) * PROCESS_QUANTITY
          console.log(processAmount)
        }

        if(checkValue.flagFrontStamping){
          console.log('flagFrontStamping')
          processAmount += parseFloat(quoteValue.frontStamping.licenceFee) + parseFloat(quoteValue.frontStamping.price) * PROCESS_QUANTITY
          console.log(processAmount)
        }

        if(checkValue.flagReverseStamping){
          console.log('flagReverseStamping')
          processAmount += parseFloat(quoteValue.reverseStamping.licenceFee) + parseFloat(quoteValue.reverseStamping.price) * PROCESS_QUANTITY
          console.log(processAmount)
        }

        if(checkValue.flagStampingNumber){
          console.log('flagStampingNumber')
          //let price = this.getPriceFromStampingSize(quoteValue.frontStamping)
          processAmount += parseFloat(quoteData.process.stampingNumber) * PROCESS_QUANTITY
          console.log(processAmount)
        }

        if(checkValue.flagColorlessBump){
          console.log('flagColorlessBump')
          //let price = this.getPriceFromStampingSize(quoteValue.frontStamping)
          processAmount += parseFloat(quoteData.process.colorlessBump) * PROCESS_QUANTITY
          console.log(processAmount)
        }

        if(checkValue.flagPressLine){
          console.log('flagPressLine')
          //let price = this.getPriceFromStampingSize(quoteValue.frontStamping)
          processAmount += parseFloat(quoteData.process.pressLine) * PROCESS_QUANTITY
          console.log(processAmount)
        }

        if(checkValue.flagBeerPinholeLine){
          console.log('flagBeerPinholeLine')
          //let price = this.getPriceFromStampingSize(quoteValue.frontStamping)
          processAmount += parseFloat(quoteData.process.beerPinholeLine) * PROCESS_QUANTITY
          console.log(processAmount)
        }

        if(checkValue.flagCut){
          console.log('flagCut')

          let {feePosition,feePerMould,cutterStart,edition,feePerPunch} = quoteData.process
          processAmount += POSITION_COUNT * parseFloat(feePosition) + (parseFloat(cutterStart)
            + parseFloat(feePerMould) * parseFloat(quoteValue.cut))
            + parseFloat(feePerPunch) + parseFloat(edition)
          console.log(processAmount)
        }

        processAmount = processAmount * parseFloat(quoteValue.style)

        const AMOUNT = parseInt(MATERIAL_AMOUNT) + parseInt(processAmount)


        if(parseInt(quoteValue.quantity) == parseInt(i)){
          postData.detail = detail
          postData.amount = AMOUNT
        }

        quoteList.push({
          quantity: QTY,
          materialAmount: parseInt(MATERIAL_AMOUNT),
          processAmount: parseInt(processAmount),
          totalAmount: AMOUNT

        })

        this.quoteList = quoteList
        this.positionCount = POSITION_COUNT
      })

    },

    caculatePositionCount(customLength,customWidth,length,width){
      let count1 = (length > customLength ? 1 : Math.ceil(customLength / length)) *
                   (width > customWidth ? 1 : Math.ceil(customWidth / width))
      let count2 = (width > customLength ? 1 : Math.ceil(customLength / width)) *
                   (length > customWidth ? 1 : Math.ceil(customWidth / length))
      return count1 >= count2 ? count2 : count1
    },

    submitOrder(){
      const {fileList,postData} = this

      if(fileList.length < 1){
        this.$message.error('请上传设计稿')
        return
      }

      let fileIds = [];
      fileList.forEach(item => {
        fileIds.push(item.id)
      })
      postData.fileIds = fileIds

      const loading = this.$loading({
        lock: true,
        text: '正在创建订单',
        spinner: 'el-icon-loading',
        background: 'rgba(0,0,0,0.7)'
      });

      postQuoteOrder(postData).then(res => {
        loading.close()
        this.$message.success('成功创建订单')
        this.$router.push({
          path: '/submitOrder',
          query: { id : res.id}
        })
      }).catch(err => {
        loading.close()
        this.$message.error('创建订单失败')
      })
    },

    handleUpload: async function(data){
      const formData = new FormData()
      formData.append('file', data.file)
      const res = await uploadFile(formData)
      let fileList = this.fileList
      fileList.push(res.file)
      this.fileList = fileList
      console.log(fileList)
    },

    getStepPriceFromList(value,list){
      let stepPrice = undefined
      list.forEach(i => {
        if(value == i.text){
          stepPrice = i.stepPrice
        }
      })
      return stepPrice
    },
  }
}
